package cn.itcast.controller;

import cn.itcast.bean.Admin;
import cn.itcast.service.AdminService;
import cn.itcast.util.DeCodeUtil;
import cn.itcast.util.JWTUtil;
import cn.itcast.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("admin")
@CrossOrigin(maxAge = 3600)//允许跨域
public class AdminController {

    //依赖注入
    @Autowired
    AdminService adminService;

//    @RequestMapping("list")
//    public List<Admin>getAdminList(){
//        List<Admin>list=adminService.list();
//        return list;
//    }

    @GetMapping("list")
    public Result getlist(){
        List<Admin> list =adminService.list();
        return Result.success(list);
    }
    @PostMapping("add")
    public Result add(@RequestBody Admin tadmin){

        String pass=tadmin.getPassword();
        String newpass=DeCodeUtil.decode(pass);
        tadmin.setPassword(newpass);

        adminService.save(tadmin);
        Admin saveadmin=adminService.getById(tadmin.getId());
        return Result.success("保存成功",saveadmin);
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id)
    {
        boolean b =adminService.removeById(id);
        if (b){
            return Result.success("删除成功");

        }
        else {
            return Result.fail(201,"删除失败");
        }
    }
    @PostMapping("edit")
    public Result edit(@RequestBody Admin tadmin)
    {
        adminService.saveOrUpdate(tadmin);
        boolean b=adminService.saveOrUpdate(tadmin);
        Admin admin1=adminService.getById(tadmin.getId());
        if(b){
            return Result.success("保存成功",admin1);
        }
        else{
            return Result.fail(201,"修改失败");
        }
    }
    @PostMapping("login")
    public Result login(Admin admin)
    {
//        验证码是否正确

//        通过用户名查询用户信息
        Admin admin2=adminService.selectByName(admin.getPhone());

//        如果有信息，就比对验证码
        if(admin2!=null){
//            加密浏览器前端传入的数据和数据库中的密码进行比较
            boolean check=DeCodeUtil.decode(admin.getPassword()).equals(admin2.getPassword());
            if(check){
                //        如果正确就登录成功,签发token
                String token= JWTUtil.getToken();
                return Result.success("登录成功",token);
            }
        }
        return Result.fail(401,"认证失败");



    }
}